package server.config;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import server.tool.Tool;

import java.io.IOException;
import java.util.List;
import java.util.Objects;

@Component
// 请求ip拦截
@PropertySource("classpath:application.yml")
public class IPRecoder implements HandlerInterceptor {

    @Resource
    private Tool tool;
    @Value("#{'${config.ip.prevent}'.split(',')}")
    public List<String> preventIp; // 阻止的ip
    @Resource
    private YamlConfig yamlConfig;

    // 注册拉拦截器
    @Override
    @SuppressWarnings("all")
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        String ip = request.getRemoteAddr(); // 获取客户端ip1
        if (Objects.isNull(ip) || StrUtil.isEmpty(ip)) {
            response.sendError(404);
            response.setCharacterEncoding(CharsetUtil.UTF_8);
            return false;
        }
        boolean notHasIp = !preventIp.contains(ip);
        boolean tokenVerity = tokenFilter(request);
        if (notHasIp && tokenVerity) {
            return true;
        } else {
            response.sendError(403);
            response.setCharacterEncoding(CharsetUtil.UTF_8);
            return false;
        }
    }

    public boolean tokenFilter(HttpServletRequest request) {
        String method = request.getMethod();
        List<String> excludesPath = yamlConfig.getExcludesList(); // 不用令牌验证的路径
        String path = request.getRequestURI();// 获取当前的路径
        if (excludesPath.contains(path)) {
            return true;
        } else {
            if (method.equalsIgnoreCase("POST")) { // 如果是post 就需要token 拦截 否则不管
                String token = request.getHeader("Token");
                return StrUtil.isNotEmpty(token) && tool.verityToken(token);
            } else {
                return true;
            }
        }
    }
}
